<template>
  <base-page v-bind="baseInfo">
    <template #searchBar>
      <filter-form
        ref="filterForm"
        :elements="elements"
        noimmediate
        @submit="handleSearch"
        @reset="handleReset"
      >
        <!-- <Button icon="add" type="plain" @click="handleAdd">新增</Button> -->
        <Button
          icon="icon-xiazai"
          type="hollow"
          :btn-loading="xzLoading"
          @click="handleDealExcel(1)"
          >下载模板</Button
        >
        <el-upload
          v-if="!imageShow"
          class="upload-demo"
          action
          accept=".xls, .xlsx"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handlechange"
        >
          <Button class="buttons" type="hollow" icon="icon-daoru" :btn-loading="drLoading"
            >导入</Button
          >
        </el-upload>
        <!-- <Button
          type="hollow"
          icon="icon-daochu1"
          :btn-loading="dcLoading"
          @click="handleDealExcel(2)"
          >导出</Button
        > -->
      </filter-form>
    </template>
    <template #content>
      <div class="table-box">
        <Table
          :columns="tableColumns"
          :loading="tableLoading"
          :data="tableData"
          :pagination="{
            total: total,
            current: currentPage,
            pageSize: pageSize,
          }"
          @paginationChange="pageChange"
        >
          <template #caozuo="{ row }">
            <Tooltip v-if="!imageShow" content="编辑" icon="edit" @click="handleEdit(row)" />
            <Tooltip v-if="!imageShow" content="删除" icon="delete" @click="handleDelete(row)" />
          </template>
        </Table>
      </div>
      <!-- 新增、编辑 -->
      <Drawer
        ref="drawerRef"
        :title="title"
        :visible.sync="showDrawer"
        width="30%"
        :footer-btns="[
          {
            text: '确认',
            type: 'primary',
            loading: qrLoading,
            trigger: 'submit',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @submit="handleSubmit"
        @cancel="showDrawer = false"
      >
        <el-form
          v-if="showDrawer"
          ref="drawerForm"
          :model="drawerForm"
          :rules="drawerRules"
          label-width="140px"
          size="mini"
          class="demo-drawerForm"
        >
          <el-form-item label="周期：" prop="period">
            <el-select
              v-model="drawerForm.period"
              placeholder="请选择"
              disabled
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in elements[0].options"
                :key="item.periodSuffix"
                :label="item.periodSuffix"
                :value="item.periodSuffix"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="核算单元名称：" prop="deptCode">
            <el-select
              v-model="drawerForm.deptCode"
              placeholder="请选择"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in elements[1].options"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="指标名称：" prop="workloadCode">
            <el-select
              v-model="drawerForm.workloadCode"
              placeholder="请选择"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in workOptions"
                :key="item.workloadCode"
                :label="item.workloadName"
                :value="item.workloadCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="工作量类型名称：" prop="workloadTypeCode">
            <el-select
              v-model="drawerForm.workloadTypeCode"
              placeholder="请选择"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in workloadTypeList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="汇总值：" prop="counts">
            <el-input
              v-model.trim="drawerForm.counts"
              placeholder="请输入"
              maxlength="20"
              clearable
              @change="handleCounts"
            />
          </el-form-item>
          <el-form-item label="点数：" prop="pionts">
            <el-input
              v-model.trim="drawerForm.pionts"
              placeholder="请输入"
              maxlength="20"
              @change="handlePionts"
              clearable
            />
          </el-form-item>
          <el-form-item label="分值：" prop="amount">
            <el-input
              v-model.trim="drawerForm.amount"
              placeholder="请输入"
              disabled
              maxlength="20"
              clearable
            />
          </el-form-item>
        </el-form>
      </Drawer>
    </template>
  </base-page>
</template>
<script>
import {
  getAssessmentCyclePull,
  listAllAccountingUnit
} from '@/api/weight'
import {
  getAssessmentCycleById
} from '@/api/targetManagement'
import {
  pageByPeriod,
  importExcel,
  importExport,
  remove,
  update,
  dataListByPeriod,
  listSysDicT
} from '@/api/dataCleaning'
export default {
  data() {
    return {
      baseInfo: {
        searchBarShow: true
      },
      dcLoading: false,
      drLoading: false,
      xzLoading: false,
      qrLoading: false,
      btnType: 1,
      drawerForm: {
        period: "",
        deptCode: "",
        workloadCode: "",
        workloadTypeCode: "",
        counts: "",
        pionts: "",
        amount: ""
      },
      drawerRules: {
        period: [{ required: true, message: "请选择周期", trigger: "change" }],
        deptCode: [{ required: true, message: "请选择核算单元名称", trigger: "change" }],
        workloadCode: [{ required: true, message: "请选择指标名称", trigger: "change" }],
        workloadTypeCode: [{ required: true, message: "请选择工作量类型名称", trigger: "change" }],
        counts: [{ required: true, message: "请输入汇总值", trigger: "blur" }],
        pionts: [{ required: true, message: "请输入点数", trigger: "blur" }],
        amount: [{ required: true, message: "请输入分值", trigger: "blur" }]
      },
      showDrawer: false,
      title: "",
      fileList: [],
      tableColumns: [
        {
          title: "核算单元名称",
          dataIndex: "deptName",
        },
        {
          title: "核算单元编码",
          dataIndex: "deptCode",
        },
        {
          title: "工作量指标名称",
          dataIndex: "workloadName",
        },
        {
          title: "工作量指标编码",
          dataIndex: "workloadCode",
        },
        {
          title: "工作量类型编码",
          dataIndex: "workloadTypeCode",
        },
        {
          title: "工作量类型名称",
          dataIndex: "workloadTypeName",
        },
        {
          title: "点数",
          dataIndex: "pionts",
        },
        {
          title: "汇总值",
          dataIndex: "counts",
        },
        {
          title: "分值",
          dataIndex: "amount",
        },
        {
          title: "操作",
          dataIndex: "caozuo",
          type: "otherTag",
          width: 160,
        },
      ],
      total: 0,
      pageSize: 100,
      currentPage: 1,
      tableLoading: false,
      tableData: [],
      newCondition: {},
      elements: [
        {
          key: "cycle",
          label: "周期",
          type: "select",
          itemLabel: "periodPull",
          itemValue: "periodSuffix",
          hideSelectAll: true,
          options: [],
          value: "",
        },
        {
          key: "accountingUnit",
          label: "核算单元名称",
          type: "select",
          itemLabel: "name",
          itemValue: "code",
          hideSelectAll: true,
          options: [],
          value: "",
        },
      ],
      currentRow: {},
      selections: [],
      indicatorList: [],
      imageShow: false,
      workOptions: [],
      workloadTypeList: []
    };
  },
  created() {
    this.getSelect();
  },
  methods: {
    getSelect() {
      // 周期
      getAssessmentCyclePull().then((res) => {
        if (res.code === 200) {
          this.elements[0].options = res.data
          const { periodSuffix } = res.data[0]
          this.elements[0].value = periodSuffix
          localStorage.setItem(
            'cycle',
            JSON.stringify(this.elements[0].options)
          )
          setTimeout(() => {
            this.handleSearch(this.$refs.filterForm.getParms())
          }, 1000)
        } else {
          this.$message.error(res.msg)
        }
      })
      // 核算单元
      listAllAccountingUnit().then((res) => {
        if (res.code === 200) {
          this.elements[1].options = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
      // 工作量类型
      listSysDicT().then(res => {
        if (res.code === 200) {
          this.workloadTypeList = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    getFileInfo() {
      const id = this.elements[0].options.find(item => item.periodSuffix === this.newCondition?.cycle)?.id
      getAssessmentCycleById({
        id: id
      }).then((res) => {
        if (res.code === 200) {
          const { isFile } = res.data
          if (isFile === 1) {
            this.imageShow = true
          } else {
            this.imageShow = false
          }
        }
      })
    },
    handleDealExcel(type) {
      // if (type === 1) {
        this.xzLoading = true;
        importExport().then((res) => {
          this.xzLoading = false;
          this.$utils.downloadFileFun(res, "手工导入.xls");
        });
      // }
    },
    // 编辑--保存
    handleSubmit() {
      this.$refs["drawerForm"].validate((valid) => {
        if (/[\u4e00-\u9fa5]+/.test(this.drawerForm.counts)) {
            this.$message.warning('汇总值不能包含中文')
            return
          } else if (!this.$isNull(this.drawerForm.counts)) {
          if (!/^([0-9]*)(\.\d{1,4})?$/.test(this.drawerForm.counts)) {
            this.$message.warning("汇总值小数位最多四位");
            return;
          }
        }
        if (/[\u4e00-\u9fa5]+/.test(this.drawerForm.pionts)) {
            this.$message.warning('点数不能包含中文')
            return
          } else if (!this.$isNull(this.drawerForm.pionts)) {
          if (!/^([0-9]*)(\.\d{1,4})?$/.test(this.drawerForm.pionts)) {
            this.$message.warning("点数小数位最多四位");
            return;
          }
        }
        if (valid) {
          const param = {
            ...this.drawerForm,
            deptName: this.elements[1].options.map(item => item.code === this.drawerForm.deptCode)?.name,
            workloadName: this.workOptions.map(item => item.workloadCode === this.drawerForm.workloadCode)?.workloadName,
            workloadTypeName: this.workloadTypeList.map(item => item.code === this.drawerForm.workloadTypeCode)?.name,
            id: this.currentRow?.id
          }
          this.qrLoading = true;
          update(param).then((res) => {
            this.qrLoading = false;
            if (res.code === 200) {
              this.getData();
              this.showDrawer = false;
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 导入
    handlechange(file, fileList) {
      // 导入
      const fileType = file.name.substr(file.name.lastIndexOf(".")).trim();
      if (fileType !== ".xlsx" && fileType !== ".xls") {
        this.$message.warning("请选择Excel格式的文件导入！");
        return;
      }
      const formData = new FormData();
      formData.append("file", file.raw);
      this.drLoading = true;
      importExcel(formData).then((res) => {
        this.drLoading = false;
        const blob = new Blob([res]);
        if (blob.size === 0) {
          this.getData();
          this.$message.success("导入成功");
        } else {
          this.$utils.downloadFileFun(res, "手工导入.xls");
        }
      });
    },
    // 查询
    handleSearch(value) {
      this.newCondition = value;
      this.currentPage = 1;
      this.getData();
      this.getFileInfo()
    },
    // 重置
    handleReset() {
      this.handleSearch();
    },
    handleEdit(row) {
      // 编辑
      this.currentRow = row;
      this.btnType = 2;
      this.title = "编辑手工导入";
      this.handleSetForm(row);
      this.drawerForm = row
      this.showDrawer = true;
       // 指标名称
       dataListByPeriod({period: this.newCondition?.cycle}).then(res => {
        if (res.code === 200) {
          this.workOptions = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleSetForm(row) {
      this.$handleSetForm(this.drawerForm, 1, row);
    },
    handleCounts(val) {
      const result = val * this.drawerForm.pionts
      this.drawerForm.amount = result.toFixed(4)
    },
    handlePionts(val) {
      const result = val * this.drawerForm.counts
      this.drawerForm.amount = result.toFixed(4)
    },
    handleDelete(row) {
      // 删除
      this.$ckConfirm({
        content: "此操作将删除该条记录，并无法恢复， 是否继续?",
        title: "提示",
        okFn: (res) => {
          remove({
            ids: row.id,
          }).then((res) => {
            if (res.code === 200) {
              this.currentPage = 1;
              this.getData();
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          });
        },
        cancelFn: (res) => {
          console.log("取消");
        },
      });
    },
    // 数据
    getData() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        period: this.newCondition?.cycle,
        deptCode: this.newCondition.accountingUnit
      };
      this.tableLoading = true;
      pageByPeriod(params)
        .then((res) => {
          this.tableLoading = false;
          if (res.code === 200) {
            this.tableData = res.data.records;
            this.total = res.data.total;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // 分页
    pageChange(payload) {
      this.currentPage = payload.current;
      this.pageSize = payload.pageSize;
      this.getData();
    },
  },
};
</script>
<style lang="less" scoped>
.table-box{
  height: 100%;
  display: flex;
  flex-direction: column;
}

</style>
